package com.bdv.md.controller;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bdv.md.model.TransHistory;
import com.bdv.md.service.TransHistoryService;

@Controller
@RequestMapping("/log")
public class LogController {
	private Logger logger = Logger.getLogger(this.getClass());
	
	private static final String LOG_FORM_PAGE = "log-form";
	private static final String LOG_HISTORY_PAGE = "log-history";

	@Autowired
	private TransHistoryService trxHstSvc;
	
	@RequestMapping("/form")
	public ModelAndView formPage(ModelAndView mav){
		mav.setViewName(LOG_FORM_PAGE);				
		return mav;
	}

	@RequestMapping("/history")
	public ModelAndView historyPage(ModelAndView mav){
		mav.setViewName(LOG_HISTORY_PAGE);				
		return mav;
	}
	
	@RequestMapping("/request-loadtransactionhistory")
	public ModelAndView requestLoadTransactionHistory(ModelAndView mav, HttpServletRequest req){
		
		String transactionId = req.getParameter("transactionId") ;		
		
		System.out.println("TX ID:#"+transactionId+"#");
		if( !transactionId.isEmpty() ) {
			System.out.println("have tx id");
			List<TransHistory> listTransactionHistory = trxHstSvc.findByTransactionId(transactionId);
			mav.addObject("logHistory", listTransactionHistory);

		}
		else {
			System.out.println("no tx id");
		
			String startDate = req.getParameter("startDate");
			String endDate = req.getParameter("endDate");
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date start=null;
			try {
				start = sdf.parse(startDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			Timestamp st = new Timestamp(start.getTime());
			
			Date end=null;
			try {
				end = sdf.parse(endDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			Timestamp en = new Timestamp(end.getTime());
			
			String type = req.getParameter("type");		
			String meterId = req.getParameter("meterId");
			
			List<TransHistory> listTransactionHistory = trxHstSvc.findByRange(st, en, type, meterId);
			mav.addObject("logHistory", listTransactionHistory);
					
		}
		
		mav.setViewName(LOG_HISTORY_PAGE);				
		return mav;
	}
}
